package com.llxz.blog.sta.controller;

import com.llxz.blog.sta.service.StaService;
import com.llxz.blog.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author lyq
 * @description: 网站统计日数据 前端控制器
 * date: 2021/9/4 8:08
 *
 */

@RestController
@RequestMapping("/sta")
public class StaController {
//   /sta/showData/{begin}/{end}
    @Autowired
    private StaService staService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("get/browse/num")
    public R getBrowseNum() {
        Integer num = Integer.valueOf(redisTemplate.opsForValue().get("browse::num"));
        return R.ok().data("browseNum",num);
    }

    @GetMapping("add/browse/num")
    public R addBrowseNum() {
        redisTemplate.opsForValue().increment("browse::num");
        return R.ok();
    }
    //统计某一天,生成统计数据
    @PostMapping("registerCount/{day}")
    public R registerCount(@PathVariable String day) {
        staService.Counts(day);
        return R.ok();
    }

    //图表显示，返回两部分数据，日期json数组，数量json数组
    @PostMapping("showData/{begin}/{end}")
    public R showData(@PathVariable String begin,
                      @PathVariable String end) {
        try {
            final Date be = new SimpleDateFormat("yyyy-MM-dd").parse(begin);
            final Date en = new SimpleDateFormat("yyyy-MM-dd").parse(end);
            System.out.println("日期为"+be+"  e nd: "+en);
            Long startTime = be.getTime();
            Long endTime = en.getTime();
            Long oneDay = 1000 * 60 * 60 * 24l;
            Long time = startTime;
            while (time <= endTime) {
                Date d = new Date(time);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//                System.out.println(df.format(d).toString());
//                staService.Counts(df.format(d).toString());
                time += oneDay;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = staService.getShowData(begin,end);
        return R.ok().data(map);
    }


}
